﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Drawing;
using Image = System.Drawing.Image;
using System.Web.UI;
using System.Data;
namespace ToolsLayer
{
    public class PublicFunction
    {
        
        public static readonly string NOT_SELECT_ITEM = "";
        
        public static DataView AddSumRow(PagedDataSource ds)
        {
            //PagedDataSource ds = datasource;
            DataView dv = (DataView)ds.DataSource;
            DataRow row = dv.Table.Rows.Add();
            object[] items = new object[dv.Table.Columns.Count];
            for (int i = 0; i < dv.Table.Columns.Count; i++)
            {
                try
                {
                    items[i] = dv.Table.Compute("sum(" + dv.Table.Columns[i].ColumnName + ")", "");
                }
                catch
                {
                    items[i] = "";
                }
            }
            row.ItemArray = items;
            return dv;
        }
        public static void BindList(System.Web.UI.WebControls.ListControl lc, 
            string sql, string data_column, string text_column)
        {
            
            BindListDefault(lc, sql, data_column, text_column);
            ListItem li = new ListItem("--请选择--", NOT_SELECT_ITEM);
            li.Selected = true;
            lc.Items.Insert(0, li);
        }

        public static void BindListDefault(System.Web.UI.WebControls.ListControl lc,
            string sql, string data_column, string text_column)
        {
            lc.ClearSelection();
            lc.DataSource = DB.ExecuteDataset(sql);
            lc.DataTextField = text_column;
            lc.DataValueField = data_column;
            lc.DataBind();
            
        }

        public static string GetTrueOrFalse_cn(string s)
        {
            if (s == "T")
                return "是";
            return "否";
        }
        public static bool IsMonth(string month)
        {
            string m = month + "-01";
            return IsDate(m);
        }
        public static void AddSelectItem(System.Web.UI.WebControls.ListControl lc)
        {
            ListItem li = new ListItem("--请选择--", NOT_SELECT_ITEM);
            li.Selected = true;
            lc.Items.Insert(0, li);
        }

        /// <summary>
        /// 是否一个字符串是数字
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsNumber(string s)
        {
            if (string.IsNullOrEmpty(s) == true) 
                return true;
            Decimal result = 0; 
            return (Decimal.TryParse(s, out result)); 
        }

        public static void SetGridViewColumnsCss(System.Web.UI.WebControls.GridView gv, string css)
        {
            for (int i = 0; i < gv.Columns.Count; i++)
            {
                gv.Columns[i].HeaderStyle.CssClass = css;
                gv.Columns[i].ItemStyle.CssClass = css;
                gv.Columns[i].FooterStyle.CssClass = css;
            }
        }
        public static void SetGridCellText(GridViewRow row, string text_ctrl_name,string value)
        {
            ITextControl c = (ITextControl)row.FindControl(text_ctrl_name);
            try
            {
                c.Text = value;
            }
            catch
            {
                throw new Exception("不能取得" + text_ctrl_name + "的文本。");
            }
        }
        public static string GetGridCellText(GridViewRow row, string text_ctrl_name)
        {
            ITextControl c = (ITextControl)row.FindControl(text_ctrl_name);
            try
            {
                return c.Text ;
            }
            catch
            {
                throw new Exception("不能取得"+text_ctrl_name+"的文本。");
            }
        }

        public static decimal decimalPrase(string s)
        {
            if (string.IsNullOrEmpty(s))
                return 0;
            return decimal.Parse(s);
        }
        public static bool IsDate(string s_date)
        {
            DateTime dt = new DateTime();
            return DateTime.TryParse(s_date, out dt);
        }

        /// <summary>
        /// 根据菜单文本递归查找菜单项
        /// </summary>
        /// <param name="mi_parent"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public static MenuItem FindMenuItemByText(System.Web.UI.WebControls.MenuItem mi_parent, string value)
        {
            if (mi_parent.Value == value)
                return mi_parent;
            if (mi_parent.ChildItems.Count == 0)
                return null;

            foreach (MenuItem mi in mi_parent.ChildItems)
            {
                if (mi.Value == value)
                    return mi;
                MenuItem ret = FindMenuItemByText(mi, value);
                if (ret != null)
                    return ret;
            }
            return null;
        }

        /// <summary>
        /// 为一张图片生成缩略图
        /// </summary>
        /// <param name="originalImagePath">图片路径</param>
        /// <param name="thumbnailPath">缩略图图片路径</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <param name="mode">模式</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = Image.FromFile(originalImagePath);
            
            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }
            //新建一个bmp图片
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

    }
}
